﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DepInnerTask.Common.Interface;
using Common.Service;
using System.Collections;
using DepInnerTask.Common.Entity;
using System.IO;
using IBatisNet.DataMapper;
using Common;
using DepInner;
namespace Ultimus.Web
{
    public partial class LogExceptionAdd : System.Web.UI.Page
    {
        IUpLoadFile upfile = ServiceContainer.GetService<IUpLoadFile>();
        IExceptionLog log = ServiceContainer.GetService<IExceptionLog>();
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();//清除缓存
            if (!IsPostBack)
            {

                if (Request.QueryString["EXCEPTION_ID"] != "" && Request.QueryString["EXCEPTION_ID"] != null)//查询详细信息
                {
                    string id = Request.QueryString["EXCEPTION_ID"];
                    BindDetails(id);
                    EnableButton();
                    hidFlag.Value = "0";//判断修改新增
                    BindFileData(id);
                }
                else //新增
                {
                    hidFlag.Value = "1";//判断修改新增
                    hidGuid.Value = Guid.NewGuid().ToString();//产生GUID唯一标示 ;
                    txtCheckDate.Text = DateTime.Now.ToShortDateString();
                    txtQueDate.Text = DateTime.Now.ToShortDateString();
                    txtQianDate.Text = DateTime.Now.ToShortDateString();
                    BindFileData(hidGuid.Value);
                }
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ExceptionLogEntity logentity = new ExceptionLogEntity();
            logentity.ACTION_BY = txtExUser.Text.Trim();
            logentity.ACTION_DATE = Convert.ToDateTime(txtExDate.Text);
            logentity.ACTION_DEPARTMENT = txtExDep.Text.Trim();
            logentity.ARBITRATE_CONCLUSION = txtJRes.Text.Trim();
            logentity.ARBITRATE_SIGN_BY = txtQianUser.Text.Trim();
            logentity.ARBITRATE_SIGN_DATE = Convert.ToDateTime(txtQianDate.Text);
            logentity.CHECK_BY = txtCheckUser.Text.Trim();
            logentity.CHECK_CONDITION = txtChBasis.Text.Trim();
            logentity.CHECK_DATE = Convert.ToDateTime(txtCheckDate.Text.Trim());
            logentity.CHECK_DESCRIPTION = txtResultDes.Text.Trim();
            logentity.CHECK_RESULT = txtChResult.Text.Trim();
            logentity.CHECK_TYPE = drpResultList.SelectedValue;
            logentity.CLOSE_STEP_NAME = txtCloseHuanjie.Text.Trim();
            logentity.CONFIRM_BY = txtQueUser.Text.Trim();
            logentity.CONFIRM_DATE = Convert.ToDateTime(txtQueDate.Text.Trim());
            logentity.CONFIRM_TYPE = drpResulList.SelectedValue;
            logentity.DOCUMENT_NUMBER = txtNo.Text.Trim();
            logentity.EXCEPTION_TYPE = drpExList.SelectedValue;
            logentity.EXCEPTOIN_CONDITION = txtExBasis.Text.Trim();
            logentity.EXCEPTOIN_REASON = txtExReason.Text.Trim();
            if (rbtnYes.Checked)
            {
                logentity.FOLLOW_UP = "1";
            }
            else
            {
                logentity.FOLLOW_UP = "2";
            }
            logentity.ILLEGAL_DEPARTMENT_NAME = txtDepName.Text.Trim();
            logentity.ILLEGAL_DEPARTMENT_REASON = txtZeCause.Text.Trim();
            logentity.ILLEGAL_TIMES = (txtCount.Text == "" )? 0 :int.Parse(txtCount.Text);
            logentity.IS_FINIAL_CONCLUSION = drpIsLastResult.SelectedValue;
            logentity.IS_ILLEGAL = drpIsExlist.SelectedValue;
            logentity.STEP_NAME = txtHuanjie.Text.Trim();
            logentity.TASK_ID = "";//传过来值
            logentity.TITLE = txtTitile.Text.Trim();
            if (hidFlag.Value == "1")
            {
                logentity.EXCEPTION_ID = hidGuid.Value;
                log.Insert(logentity);
                MessageBox("添加信息成功！");
            }
            else
            {
                logentity.EXCEPTION_ID = Request.QueryString["EXCEPTION_ID"];
                log.Update(logentity);
                MessageBox("修改成功！");
            }
           
            //Response.Redirect("LogExceptionAdd.aspx");
        }
        #region 封装弹出信息
        private void MessageBox(string name)
        {
            Response.Write("<script type='text/javascript'>alert('" + name + "');window.close();</script>");
        }
        #endregion

        #region 绑定详细信息
        private void BindDetails(string id)
        {
           
            ExceptionLogEntity logentity = log.Get(id);
            txtExUser.Text = logentity.ACTION_BY;
            if (logentity.ACTION_DATE.ToString() != "")
            {
                DateTime dt = DateTime.Parse(logentity.ACTION_DATE.ToString());
                txtExDate.Text = dt.ToString("yyyy-MM-dd");
            }
            txtExDep.Text = logentity.ACTION_DEPARTMENT;
            txtJRes.Text = logentity.ARBITRATE_CONCLUSION;
            txtQianUser.Text = logentity.ARBITRATE_SIGN_BY;
            if (logentity.ARBITRATE_SIGN_DATE.ToString() != "")
            {
                DateTime dt1 = DateTime.Parse(logentity.ARBITRATE_SIGN_DATE.ToString());
                txtQianDate.Text = dt1.ToString("yyyy-MM-dd");
            }
            txtCheckUser.Text = logentity.CHECK_BY;
            txtChBasis.Text = logentity.CHECK_CONDITION;
            if (logentity.CHECK_DATE.ToString() != "")
            {
                DateTime dt2 = DateTime.Parse(logentity.CHECK_DATE.ToString());
                txtCheckDate.Text = dt2.ToString("yyyy-MM-dd");
            }
            txtResultDes.Text = logentity.CHECK_DESCRIPTION;
            txtChResult.Text = logentity.CHECK_RESULT;
            drpResultList.SelectedValue = logentity.CHECK_TYPE;
            txtCloseHuanjie.Text = logentity.CLOSE_STEP_NAME;
            txtQueUser.Text = logentity.CONFIRM_BY;
            if (logentity.CONFIRM_DATE.ToString() != "")
            {
                DateTime dt3 = DateTime.Parse(logentity.CONFIRM_DATE.ToString());
                txtQueDate.Text = dt3.ToString("yyyy-MM-dd");
            }
            txtTaskNo.Text = logentity.TASK_ID;
            drpResulList.SelectedValue = logentity.CONFIRM_TYPE;
           // drpResulList.SelectedItem.Value = logentity.CONFIRM_TYPE;
            txtNo.Text = logentity.DOCUMENT_NUMBER;
            // logentity.EXCEPTION_ID = Guid.NewGuid().ToString();
            drpExList.SelectedValue = logentity.EXCEPTION_TYPE;
            txtExBasis.Text = logentity.EXCEPTOIN_CONDITION;
            txtExReason.Text = logentity.EXCEPTOIN_REASON;
            if (logentity.FOLLOW_UP == "1")
            {
                rbtnYes.Checked = true;
                rbtnNo.Checked = false;
            }
            else
            {
                rbtnNo.Checked = true;
                rbtnYes.Checked = false;
            }
            txtDepName.Text = logentity.ILLEGAL_DEPARTMENT_NAME;
            txtZeCause.Text = logentity.ILLEGAL_DEPARTMENT_REASON;
            txtCount.Text = logentity.ILLEGAL_TIMES.ToString();
            drpIsLastResult.SelectedValue = logentity.IS_FINIAL_CONCLUSION;
            drpIsExlist.SelectedValue = logentity.IS_ILLEGAL;
            txtHuanjie.Text = logentity.STEP_NAME;
            //logentity.TASK_ID = "";//传过来值
            txtTitile.Text = logentity.TITLE;
            if (logentity.IS_FINIAL_CONCLUSION == "1")//【是否为最终核查结果】为【是】时，流程管理方核查记录仅可读，不可编辑。
            {
                EnableButtonALL();
            }
        }
        #endregion
        #region 按钮不可用
        private void EnableButtonALL()
        {
            txtExUser.Enabled = false;
            txtExDate.Enabled = false;
            txtExDep.Enabled = false;
            txtJRes.Enabled = false;
            txtQianUser.Enabled = false;
            txtQianDate.Enabled = false;
            txtCheckUser.Enabled = false;
            txtChBasis.Enabled = false;
            txtCheckDate.Enabled = false;
            txtResultDes.Enabled = false;
            txtChResult.Enabled = false;
            drpResultList.Enabled = false;
            txtCloseHuanjie.Enabled = false;
            txtQueUser.Enabled = false;
            txtQueDate.Enabled = false;
            txtTaskNo.Enabled = false;
            drpResulList.Enabled = false;
            txtNo.Enabled = false;
            // logentity.EXCEPTION_ID = Guid.NewGuid().ToString();
            drpExList.Enabled = false;
            txtExBasis.Enabled = false;
            txtExReason.Enabled = false;
            rbtnNo.Enabled = false;
            rbtnYes.Enabled = false;
            txtDepName.Enabled = false;
            txtZeCause.Enabled = false;
            txtCount.Enabled = false;
            drpIsLastResult.Enabled = false;
            drpIsExlist.Enabled = false;
            txtHuanjie.Enabled = false;
            //logentity.TASK_ID = "";//传过来值
            txtTitile.Enabled = false;
            this.btnSubmit.Enabled = false;
            btnCancle.Enabled = false;
            btnUpload.Enabled = false;
            gvUpLoadFile.Enabled = false;
        }

        #endregion
        #region 按钮不可用 用户点击【查看详细】按钮后，显示此实例异常日志。其中流程异常原始记录信息仅可读，不可编辑()
        private void EnableButton()
        {
            txtNo.Enabled = false;
            txtTitile.Enabled = false;
            drpExList.Enabled = false;
            txtHuanjie.Enabled = false;
            txtTaskNo.Enabled = false;
            txtCloseHuanjie.Enabled = false;
            txtExUser.Enabled = false;
            txtExDep.Enabled = false;
            txtExDate.Enabled = false;
            txtExReason.Enabled = false;
            txtExBasis.Enabled = false;
            rbtnYes.Enabled = false;
            rbtnNo.Enabled = false;
        }

        #endregion
        protected void btnCancle_Click(object sender, EventArgs e)
        {
            Response.Redirect("LogExceptionAdd.aspx");
        }

         /// <summary>
        /// 绑定GridView
        /// </summary>
        private void BindFileData(string id)
        {
            IList list = upfile.GetList(id);
            this.gvUpLoadFile.DataSource = list;
            this.gvUpLoadFile.DataBind();
        }

        /// <summary>
        /// 点击上传附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //判断是否上传了文件 
            if (file.HasFile)
            {
                //指定上传文件在服务器上的保存路径 
                string savePath = Server.MapPath("UpLoad/");
                //检查服务器上是否存在这个物理路径，如果不存在则创建 
                if (!System.IO.Directory.Exists(savePath))
                {
                    //需要注意的是，需要对这个物理路径有足够的权限，否则会报错 
                    //另外，这个路径应该是在网站之下，而将网站部署在C盘却把上传文件保存在D盘 
                    System.IO.Directory.CreateDirectory(savePath);
                }
                savePath = savePath + "\\" + file.FileName;
                file.SaveAs(savePath);//保存文件 
                //不过需要注意的是，在客户端访问却需要指定的是URL地址，而不是在服务器上的物理地址 
               // literal.Text = string.Format("<a href='upload/{0}'>upload/{0}</a>", file.FileName);
                //插入数据库数据
                UpLoadFileEntity fileEntity = new UpLoadFileEntity();
                fileEntity.FILE_NAME = file.FileName;
                fileEntity.FILE_SAVEPATH = file.FileName;
                if (hidFlag.Value == "1")//新增
                {
                    fileEntity.GUID = hidGuid.Value;//来源ID
                }
                else
                {
                    fileEntity.GUID = Request.QueryString["EXCEPTION_ID"];//修改
                }
                fileEntity.IS_ACTIVE = "0";//0未激活 1已激活 2失效 
                fileEntity.PROCESS_NAME = Request.QueryString["ProcessName"];
                fileEntity.UPLOAD_BY ="";//发起人
                fileEntity.UPLOAD_DATE = DateTime.Now;
                fileEntity.UPLOAD_FILE_ID = Guid.NewGuid().ToString();//主键
                fileEntity.UPLOAD_FILE_TYPE = "";//附件类型
                upfile.Insert(fileEntity);
                BindFileData(fileEntity.GUID);
            }
        }
        protected void gvUpLoadFile_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            //如果是绑定数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    ((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除：" + e.Row.Cells[1].Text.Trim() + "吗?')");
                }
            }
        }
        protected void gvUpLoadFile_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            string id = this.gvUpLoadFile.DataKeys[e.RowIndex].Value.ToString();

            //同事删除文件夹中文件
            IList list = upfile.GetList1(id);
            if (list.Count > 0)
            {
                var fileName = ((UpLoadFileEntity)(list[0])).FILE_NAME;
                string pSavedPath1 = Server.MapPath("UpLoad/" + fileName);
                if (File.Exists(pSavedPath1))
                {
                    FileInfo fi = new FileInfo(pSavedPath1);
                    File.Delete(pSavedPath1);
                }
            }
            upfile.Delete(id);
            Response.Redirect(Request.RawUrl);

        }
    }
}